package com.samnative.pineapple.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.pay.AliPayHelper;
import com.android.pay.IPayCallBack;
import com.android.pay.WXPayHelper;
import com.samnative.pineapple.entity.UserModel;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.GsonUtils;
import com.samnative.pineapple.utils.MD5Util;
import com.samnative.pineapple.value.Config;
import com.samnative.pineapple.widget.InputPasswordPop;
import com.google.gson.reflect.TypeToken;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.shashank.sony.fancytoastlib.FancyToast;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ezy.ui.view.RoundButton;


/**
 * 收银台=>支持原生SDK接的支付宝和微信支付
 */
public class ChoosePayActivity extends BaseActivity implements View.OnClickListener {


    private Context context;
    /**
     * 支付方式按钮
     */
    private LinearLayout llBalance, llWeichat, llAlipay;
    /**
     * 支付订单号
     */
    private String orderNo;
    /**
     * 当前选中的支付类型
     */
    private int currentPayType = -1;
    /**
     * 支付方式余额支付
     */
    public static final int PAY_BALANCE = 1;
    /**
     * 支付方式微信
     */
    public static final int PAY_WEICHAT = 2;
    /**
     * 支付方式支付宝
     */
    public static final int PAY_ALIPAY = 3;
    /**
     * 是否已微信安装
     */
    private boolean isInstallWeiChat;
    /**
     * 显示勾选
     */
    private ImageView iv_choose_balance, iv_choose_wechat, iv_choose_ali;
    /**
     * 订单类型 1商城 2实体店 3用户充值
     */
    private int orderType;
    /**
     * 显示余额支付的名称和余额不足
     */
    private TextView tv_balance, tv_balance_not;
    /**
     * 总价显示
     */
    private TextView amount_tv;
    /**
     * 确认按钮
     */
    private RoundButton btn_pay;
    /**
     * 支付配置列表
     */
    private List<Paytmethod> paytmethods;
    /**
     * 输入密码控件
     */
    private InputPasswordPop inputPp;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_choosepay;
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        context = this;
        paytmethods = new ArrayList<>();
        findViewById(R.id.tv_back).setOnClickListener(this);
        this.orderNo = getIntent().getStringExtra("orderNo");
        this.orderType = getIntent().getIntExtra("orderType", 1);

        btn_pay = (RoundButton) findViewById(R.id.btn_pay);
        btn_pay.setOnClickListener(this);
        llBalance = (LinearLayout) findViewById(R.id.ll_pay_balance);
        llBalance.setOnClickListener(this);
        llWeichat = (LinearLayout) findViewById(R.id.ll_pay_weichat);
        llWeichat.setOnClickListener(this);
        llAlipay = (LinearLayout) findViewById(R.id.ll_pay_alipay);
        llAlipay.setOnClickListener(this);

        iv_choose_balance = (ImageView) findViewById(R.id.iv_choose_balance);
        iv_choose_wechat = (ImageView) findViewById(R.id.iv_choose_wechat);
        iv_choose_ali = (ImageView) findViewById(R.id.iv_choose_ali);

        tv_balance_not = (TextView) findViewById(R.id.tv_balance_not);
        tv_balance = findViewById(R.id.tv_balance);
        amount_tv = (TextView) findViewById(R.id.amount_tv);
//        amount_tv.setText("¥" + amount);
        // 判断微信是否安装
        IWXAPI m_IWXAPI = WXAPIFactory.createWXAPI(context, null);
        m_IWXAPI.registerApp(Config.wechatId);
        if (m_IWXAPI.isWXAppInstalled() || m_IWXAPI.isWXAppInstalled()) {
            isInstallWeiChat = true;
        }


    }

    @Override
    public void onBackPressed() {

        MessageDialog.show(this, null, "确定要放弃付款吗？", getString(R.string.confirm), getString(R.string.cancel)).setOnOkButtonClickListener(
                new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        if (orderType == 1) {
                            Intent intent = new Intent();
                            intent.putExtra("resultCode", -2);
                            setResult(220, intent);
                        }
                        finish();
                        return false;
                    }
                });

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.tv_back:
                MessageDialog.show(this, null, "确定要放弃付款吗？", getString(R.string.confirm), getString(R.string.cancel)).setOnOkButtonClickListener(
                        new OnDialogButtonClickListener() {
                            @Override
                            public boolean onClick(BaseDialog baseDialog, View v) {
                                if (orderType == 1) {
                                    Intent intent = new Intent();
                                    intent.putExtra("resultCode", -2);
                                    setResult(220, intent);
                                }
                                finish();
                                return false;
                            }
                        });

                break;
            case R.id.ll_pay_balance:
//                if (!tv_balance_not.getText().toString().isEmpty() && !tv_balance_not.getText().toString().contains("积分")) {
//                    btn_pay.setText("去充值");
//                } else {
                btn_pay.setText("确认付款");
//                }
                setChooseView(iv_choose_balance);
                currentPayType = PAY_BALANCE;
                break;
            case R.id.ll_pay_weichat:
                btn_pay.setText("确认付款");
                setChooseView(iv_choose_wechat);
                currentPayType = PAY_WEICHAT;
                break;
            case R.id.ll_pay_alipay:
                btn_pay.setText("确认付款");
                setChooseView(iv_choose_ali);
                currentPayType = PAY_ALIPAY;
                break;

            case R.id.btn_pay:

                UserModel userModel=AppPrefer.getUserModel(context);
                if (userModel.getData().getPayDec().equals("0")) {
                    MessageDialog.show(this, null, "您还未设置资金密码，请前往安全中心设置", getString(R.string.confirm), getString(R.string.cancel)).setOnOkButtonClickListener(
                            new OnDialogButtonClickListener() {
                                @Override
                                public boolean onClick(BaseDialog baseDialog, View v) {
                                    startActivity(new Intent(mContext, SecurityCenterActivity.class));
                                    return false;
                                }
                            });
                    return;
                }

                switch (currentPayType) {
                    case PAY_BALANCE:
                        balancePay();
                        break;
                    case PAY_WEICHAT:
                        if (!isInstallWeiChat) {
                            FancyToast.showToast(mContext, "请安装微信app", FancyToast.WARNING, false);
                            break;
                        }
                        requestPlayInfo(orderNo, "weixin");
                        break;
                    case PAY_ALIPAY:
                        requestPlayInfo(orderNo, "ali");
                        break;
                    default:
                        break;
                }
                break;
        }
    }


    /**
     * 设置选中效果
     *
     * @param iv
     */
    public void setChooseView(ImageView iv) {

        if (iv.getTag().toString().length() > 0) {
            return;
        }


        iv_choose_wechat.setImageResource(0);
        iv_choose_ali.setImageResource(0);
        iv_choose_balance.setImageResource(0);

        iv.setImageResource(R.mipmap.ic_pay_check);
    }


    /**
     * 获取付款信息
     */
    private void requestPlayInfo(String orderOn, String playType) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("orderno", orderOn);
        map.put("pay_type", playType);
        map.put("_apiname", "pay.pay.request");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONObject jsonData = result;
                    switch (currentPayType) {
                        case PAY_WEICHAT:// 调用微信支付
                            weichatPay(jsonData.getJSONObject("data")
                                    .toString());
                            break;
                        case PAY_ALIPAY:// 调用支付宝支付
                            aliPay(jsonData.getJSONObject("data")
                                    .getString("param"));
                            break;
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });


    }

    /**
     * 支付宝支付
     *
     * @param orderInfo
     */
    public void aliPay(String orderInfo) {
        AliPayHelper m_AliPayHelper = new AliPayHelper(context, orderInfo,
                iPayCallBack);
        m_AliPayHelper.startPay();
    }

    /**
     * 微信支付
     *
     * @param json
     */
    public void weichatPay(String json) {
        WXPayHelper m_WXPayHelper = new WXPayHelper(context, json, iPayCallBack);
        m_WXPayHelper.sendPayReq();
    }


    /**
     * 支付结果回调
     * <p>
     * (包含支付宝，微信，余额支付结果，不包含通联支付)
     */
    IPayCallBack iPayCallBack = new IPayCallBack() {

        @Override
        public void payCallBack(int p_result) {
            // TODO Auto-generated method stub
            if (p_result == -2) {
                return;
            }
            if (p_result == 0) {
                FancyToast.showToast(mContext, "支付成功", FancyToast.SUCCESS, false);
            }
            Intent intent = new Intent();
            intent.putExtra("resultCode", p_result);
            setResult(220, intent);
            finish();
        }
    };

    /**
     * 支付结果回调（通联支付）
     *
     * @param arg0
     * @param arg1
     * @param data
     */
    @Override
    protected void onActivityResult(int arg0, int arg1, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(arg0, arg1, data);


    }


    /**
     * 获取支付配置
     */
    private void requestPlayMethod() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("orderno", orderNo);
        map.put("_apiname", "pay.pay.paytmethod");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONObject jsonData = result.getJSONObject("data");
                    JSONArray jsonPaytmethod = jsonData.getJSONArray("paytmethod");

                    paytmethods = GsonUtils
                            .fromJsonList(jsonPaytmethod.toString(), new TypeToken<List<Paytmethod>>() {
                            }.getType());

                    for (int i = 0; i < paytmethods.size(); i++) {
                        Paytmethod model = paytmethods.get(i);

                        if (model.getCode().equals("ali")) {
                            //是否支持支付宝
                            if (model.getIsshow().equals("1")) {
                                llAlipay.setVisibility(View.VISIBLE);
                                if (currentPayType == -1) {
                                    setChooseView(iv_choose_ali);
                                    currentPayType = PAY_ALIPAY;
                                }
                            } else {
                                llAlipay.setVisibility(View.GONE);
                            }
                        }
                        if (model.getCode().equals("weixin")) {
                            //是否支持微信支付
                            if (model.getIsshow().equals("1")) {
                                llWeichat.setVisibility(View.VISIBLE);
                                if (currentPayType == -1) {
                                    setChooseView(iv_choose_wechat);
                                    currentPayType = PAY_WEICHAT;
                                }
                            } else {
                                llWeichat.setVisibility(View.GONE);
                            }
                        }
                        if (model.getCode().equals("blance")) {
                            //是否支持余额
                            if (model.getIsshow().equals("1")) {
                                llBalance.setVisibility(View.VISIBLE);
                                tv_balance_not.setText(model.getStatus());
                                tv_balance.setText(model.getPayname());
                                if (currentPayType == -1) {
                                    setChooseView(iv_choose_balance);
                                    currentPayType = PAY_BALANCE;
                                }
                            } else {
                                llBalance.setVisibility(View.GONE);
                            }
                        }
                    }

                    String amount = jsonData.optString("pay_amount");
                    if (!TextUtils.isEmpty(amount)) {
                        amount_tv.setText("¥" + amount);
                    } else {
                        amount_tv.setText("¥0");
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });


    }


    /**
     * 判断条件后调用余额或积分支付
     */
    public void balancePay() {

//        //余额不足
//        if (currentPayType == PAY_BALANCE && !tv_balance_not.getText().toString().isEmpty()) {
//            Intent intent = new Intent(context, MyCashActivity.class);
//            context.startActivity(intent);
//            return;
//        }


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                inputPp = new InputPasswordPop(context, new InputPasswordPop.OnResult() {
                    @Override
                    public void password(String password) {
                        requestPlayBalance(password);
                    }
                });
                inputPp.showAtLocation(btn_pay, Gravity.CENTER, 0, 0);
            }
        }, 100);

    }

    /**
     * 发起余额付款
     */

    private void requestPlayBalance(String pwd) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        map.put("orderno", orderNo);
        map.put("paypwd", MD5Util.getMD5Str(pwd));
        String api = "";
        if (currentPayType == PAY_BALANCE) {
            api = "pay.pay.balancepay";
        }
        map.put("_apiname", api);
        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                FancyToast.showToast(mContext, "支付成功", FancyToast.SUCCESS, false);
                iPayCallBack.payCallBack(0);
                if (!isFinishing() && inputPp != null && inputPp.isShowing()) {
                    inputPp.dismiss();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);
                if (code == 50000) {
                    // 密码错误超三次

                    MessageDialog.show(ChoosePayActivity.this, null, "密码输入错误三次,请重新设置!", getString(R.string.confirm), getString(R.string.cancel)).setOnOkButtonClickListener(
                            new OnDialogButtonClickListener() {
                                @Override
                                public boolean onClick(BaseDialog baseDialog, View v) {

                                    Intent intent = new Intent().setClass(mContext, PasswordLoginVerityActivity.class);
                                    intent.putExtra("type", 4);
                                    startActivity(intent);
                                    return false;
                                }
                            });


                }
//                else {
//                    // 获取付款参数接口调用失败,视作付款失败
//                    iPayCallBack.payCallBack(-1);
//                }

            }
        });

    }

//    /**
//     * 检查并申请权限
//     */
//    public void getPermissions() {
//        // 要申请的权限
//        String[] permissions = {Manifest.permission.READ_PHONE_STATE};
//        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            // 检查该权限是否已经获取
//            int a = ContextCompat.checkSelfPermission(this, permissions[0]);
//            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
//            if (a != PackageManager.PERMISSION_GRANTED) {
//                // 如果没有授予该权限，就去提示用户请求
//                ActivityCompat.requestPermissions(this, permissions, 999);
//            }
//        }
//    }
//
//    /**
//     * 权限申请回调
//     *
//     * @param requestCode
//     * @param permissions
//     * @param grantResults
//     */
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == 999 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//            //成功获得权限
//        }
//    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestPlayMethod();
    }


    /**
     * 支付方式model
     * "isshow": "1",
     * "code": "blance",
     * "payname": "余额支付",
     * "canchoose": "0"
     * "status":""
     */
    public class Paytmethod {

        private String isshow;
        private String code;
        private String payname;
        private String canchoose;
        private String status;

        public String getIsshow() {
            return isshow;
        }

        public void setIsshow(String isshow) {
            this.isshow = isshow;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getPayname() {
            return payname;
        }

        public void setPayname(String payname) {
            this.payname = payname;
        }

        public String getCanchoose() {
            return canchoose;
        }

        public void setCanchoose(String canchoose) {
            this.canchoose = canchoose;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }
    }

}
